package com.breakfast.fun.ui.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.breakfast.fun.App;
import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.adapter.home.HomeTypeAdapter;
import com.breakfast.fun.base.BaseFragment;
import com.breakfast.fun.data.entity.home.ActivityAd;
import com.breakfast.fun.data.entity.home.CenterAd;
import com.breakfast.fun.data.entity.home.CityData;
import com.breakfast.fun.data.entity.home.FourAd;
import com.breakfast.fun.data.entity.home.Home;
import com.breakfast.fun.data.entity.home.Notice;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.ProductClasses;
import com.breakfast.fun.data.entity.home.Version;
import com.breakfast.fun.data.entity.home.product.ProductDetail;
import com.breakfast.fun.data.entity.home.product.ProductState;
import com.breakfast.fun.data.entity.home.product.WeekdayState;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.event.ScrollEvent;
import com.breakfast.fun.event.UpdateEvent;
import com.breakfast.fun.ui.other.city.CityActivity;
import com.breakfast.fun.ui.user.cart.UserCartActivity;
import com.breakfast.fun.util.ColorUtil;
import com.breakfast.fun.util.DensityUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.SharedUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.util.VersionUtil;
import com.breakfast.fun.view.layout.HomeHeaderBanner;
import com.breakfast.fun.view.layout.HomeHeaderIcons;
import com.breakfast.fun.view.widget.CustomDialog;
import com.breakfast.fun.view.widget.SmoothListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by hp on 2016/8/16.
 */
public class HomeFragment extends BaseFragment<HomePresenter, HomeModel> implements HomeContract.View {
//厉害的啊

    @Bind(R.id.slv_home)
    SmoothListView slvHome;
    @Bind(R.id.tv_home_city)
    TextView tvHomeCity;
    @Bind(R.id.rl_home_title)
    RelativeLayout rlHomeTitle;
    @Bind(R.id.ll_fragment_home_cart)
    LinearLayout mLlFragmentHomeCart;
    @Bind(R.id.tl_fragment_home)
    TabLayout mTlFragmentHomeTop;
    @Bind(R.id.tv_fragment_home_cart_price)
    TextView mTvFragmentHomeCartPrice;
    @Bind(R.id.tv_fragment_home_cart_count)
    TextView mTvFragmentHomeCartCount;
    @Bind(R.id.iv_fragment_home_cart)
    ImageView mIvFragmentHomeCart;
    @Bind(R.id.fl_home)
    FrameLayout mFlHome;
    @Bind(R.id.iv_to_top)
    ImageView mIvToTop;

    public static boolean isNeedRefresh = false;
    private static boolean isFristLoadAd = true;
    public static boolean isNeedShowAd = true;

    private static boolean isLoadFailure = false;
    public static boolean isChangeCity = false;

    private boolean isScrollIdle = true;    // ListView是否在滑动
    private boolean isStickyTop = false;    // 是否吸附在顶部
    private int titleViewHeight = 48;       // 标题栏的高度（单位dp）

    private int adViewHeight = 180; // 广告视图的高度
    private int adViewTopSpace;     // 广告视图距离顶部的距离

    private int hotNewTabViewTopSpace;  // 本周热卖tab距离顶部的距离
    private int homeheadIconsHeight;    // 分类 + 活动 + 热卖新品 总高度
    private int homeheadIconsTabHeight; // 本周热卖tab高度


    private HomeHeaderBanner homeHeaderBanner;      //首页广告视图
    //    private HomeHeaderGallery homeHeaderGallery;    //首页周套餐画廊及滚动text
    private HomeHeaderIcons homeHeaderIcons;        //首页横向滑动分类按钮

    private HomeTypeAdapter homeTypeAdapter;

    private List<Product> hotProducts = new ArrayList<Product>();
    private List<Product> newProducts = new ArrayList<Product>();
    private List<Product> curProducts = new ArrayList<Product>();       //用来存放hotProducts前10个的容器
    private int curPosition = 0;

    public static String chooseDate = "";

    public static String localCode = "";


    private int page = 1;
    private boolean isDownLoad = false;
    private Notification mNotification;
    private NotificationManager mNotificationManager;
    private static final int NOTIFY_ID = 0;
    private Dialog dialog;
    private File savePath;
    private File saveFileName;


    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case VersionUtil.VERSION_RESULT:
                    int arg1 = msg.arg1;
                    int arg2 = msg.arg2;
                    if (arg1 == 0) {
                        if (arg2 == 0) {
                        } else {
                            if (!isDownLoad) {
                                final Version.DataBean version = (Version.DataBean) msg.obj;
                                dialog = new CustomDialog(getActivity(),
                                        R.style.dialog_style,
                                        R.layout.dialog_custom, "更新提醒",
                                        "发现新版本:" + version.getAndroid() + "\n更新内容:"
                                                + version.getAndroidContent()
                                                + ",是否下载更新? ",
                                        version.getAndroidFlag() == 1,
                                        false,
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();
                                                mNotificationManager = (NotificationManager) getActivity()
                                                        .getSystemService(
                                                                Context.NOTIFICATION_SERVICE);
                                                savePath = new File(
                                                        Environment
                                                                .getExternalStorageDirectory(),
                                                        "zaofan/");// 外存根目录下的文件夹
                                                saveFileName = new File(
                                                        Environment
                                                                .getExternalStorageDirectory(),
                                                        "zaofan/zaofan.apk");// 外存根目录下的文件夹
                                                setUpNotification();

//                                                else{
                                                VersionUtil.updateVersion(context,
                                                        savePath, saveFileName,
                                                        version.getAndroidUrl(),
                                                        handler,
                                                        version.getAndroid());
                                                isDownLoad = true;
//                                                }
                                            }
                                        });
                                // if (version.getAndroidFlag() == 1) {
                                // dialog.setCancelable(false);
                                // }
                                dialog.show();
                                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        if (version.getAndroidFlag() == 1) {
                                            // 不可取消
                                            if (!isDownLoad) {// 未下载
                                                getActivity().finish();
                                            }
                                        }
                                    }
                                });
                            } else {
                                T.show("正在下载...");
                            }

                        }
                    } else {
                        T.show(msg.obj.toString());
                    }
                    break;
                case VersionUtil.VERSION_DOWN:
                    int rate = msg.arg1;
                    if (rate < 100) {
                        RemoteViews contentview = mNotification.contentView;
                        contentview.setTextViewText(R.id.tv_progress, rate + "%");
                        contentview.setProgressBar(R.id.progressbar, 100, rate,
                                false);
                    } else {
                        // 下载完毕后变换通知形式
                        mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                        mNotification.contentView = null;
                        // mNotification.setLatestEventInfo(getActivity(), "下载完成",
                        // "文件已下载完毕", null);
                        Notification.Builder builder = new Notification.Builder(
                                getActivity());
                        builder.setContentTitle("下载完成");
                        builder.setContentText("文件已下载完毕");
                        builder.setSmallIcon(R.mipmap.ic_launcher);
                        mNotification = builder.getNotification();
                    }
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    break;
                case VersionUtil.VERSION_DOWNED:
                    // 下载后关闭应用 安装新应用
                    getActivity().finish();
                    isDownLoad = false;
                    mNotificationManager.cancel(NOTIFY_ID);
                    VersionUtil.installApk(saveFileName, getActivity());
                    break;
                case VersionUtil.VERSION_DOWN_FAIL:
                    isDownLoad = false;
                    mNotificationManager.cancel(NOTIFY_ID);
                    T.show("网络出错,下载失败!");
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);

        CityData cityData = CityData.objectFromData(SharedUtil.getString(context, "city"));

        if (cityData != null) {
            tvHomeCity.setText(cityData.getCityName());
        } else {
            tvHomeCity.setText("请选择城市");
        }

        mTlFragmentHomeTop.addTab(mTlFragmentHomeTop.newTab().setText("本周热卖"));
        mTlFragmentHomeTop.addTab(mTlFragmentHomeTop.newTab().setText("人气新品"));
        mTlFragmentHomeTop.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0 && curPosition != 0) {
                    slvHome.setLoadMoreEnable(true, false);
                    homeTypeAdapter.setAdapterType(1);
                    homeHeaderIcons.setCurPosition(tab.getPosition());
                    curProducts.clear();
                    curProducts.addAll(hotProducts);
                    homeTypeAdapter.notifyDataSetChanged();
                    curPosition = 0;
                } else if (tab.getPosition() == 1 && curPosition != 1) {
                    slvHome.setLoadMoreEnable(false, false);
                    homeTypeAdapter.setAdapterType(2);
                    homeHeaderIcons.setCurPosition(tab.getPosition());
                    curProducts.clear();
                    curProducts.addAll(newProducts);
                    homeTypeAdapter.notifyDataSetChanged();
                    curPosition = 1;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        slvHome.setOnScrollListener(new SmoothListView.OnSmoothScrollListener() {
            @Override
            public void onSmoothScrolling(View view) {

            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

//                if (isScrollIdle && adViewTopSpace < 0) return;

//                if (homeHeaderGallery != null) {
//                    adViewTopSpace = (int) DensityUtil.px2dp(context, homeHeaderGallery.getSpaceTop());
//                    adViewHeight = (int) DensityUtil.px2dp(context, homeHeaderGallery.getHeight());
//                }

                //asdf
                if (homeHeaderBanner != null) {
                    adViewTopSpace = (int) DensityUtil.px2dp(context, homeHeaderBanner.getSpaceTop());
                    adViewHeight = (int) DensityUtil.px2dp(context, homeHeaderBanner.getHeight());
                }
                if (homeHeaderIcons != null) {
                    hotNewTabViewTopSpace = (int) DensityUtil.px2dp(context, homeHeaderIcons.getSpaceTop());
                    homeheadIconsHeight = (int) DensityUtil.px2dp(context, homeHeaderIcons.getHeight());
                    homeheadIconsTabHeight = (int) DensityUtil.px2dp(context, homeHeaderIcons.getTlHotNewHeight());

//                    L.d("hotNewTabViewTopSpace----" + hotNewTabViewTopSpace + ", homeheadIconsHeight----" + homeheadIconsHeight
//                     + " ,homeheadIconsTabHeight---" + homeheadIconsTabHeight);
                    boolean s = hotNewTabViewTopSpace + 1 <= -homeheadIconsHeight + homeheadIconsTabHeight;
//                    L.d("result--" + s);
//                    L.d("firstVisibleItem---" + firstVisibleItem + ",visibleItemCount---" + visibleItemCount + ",totalItemCount---" + totalItemCount);
                }


                if (hotNewTabViewTopSpace + 1 <= -homeheadIconsHeight + homeheadIconsTabHeight) {
                    mTlFragmentHomeTop.setVisibility(View.VISIBLE);
                    mIvToTop.setVisibility(View.VISIBLE);
                } else {
                    mTlFragmentHomeTop.setVisibility(View.GONE);
                    mIvToTop.setVisibility(View.GONE);
                }
//                handleTitleBarColorEvaluate();
            }

        });


        tvHomeCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CityActivity.class);
                startActivity(intent);
            }
        });
        //访问访问失败时，不会显示加载更多
        slvHome.setLoadMoreEnable(false, false);

        slvHome.setSmoothListViewListener(new SmoothListView.ISmoothListViewListener() {
            @Override
            public void onRefresh() {
                presenter.refresh();
                isNeedShowAd = false;
            }

            @Override
            public void onLoadMore() {
                presenter.loadMore(page++);
            }
        });

        mLlFragmentHomeCart.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setClass(getActivity(), UserCartActivity.class);
            startActivity(intent);

//            Intent localIntent = new Intent();
//            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            if (Build.VERSION.SDK_INT >= 9) {
//                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
//            } else if (Build.VERSION.SDK_INT <= 8) {
//                localIntent.setAction(Intent.ACTION_VIEW);
//                localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
//                localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//            }
//            startActivity(localIntent);

//            dialog = new AlertDialog.Builder(context).setTitle("请允许获取读写存储卡信息")
//                    .setMessage("点击确定进入权限管理打开访问存储功能，是否手动授权?")
//                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            Intent localIntent = new Intent();
//                            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            if (Build.VERSION.SDK_INT >= 9) {
//                                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
//                            } else if (Build.VERSION.SDK_INT <= 8) {
//                                localIntent.setAction(Intent.ACTION_VIEW);
//                                localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
//                                localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//                            }
//                            startActivity(localIntent);
//                        }
//                    })
//                    .setCancelable(false).create();

//            dialog = new CustomDialog(context, R.style.dialog_style,
//                    R.layout.dialog_custom, "请允许获取读写存储卡信息", "点击确定进入权限管理打开访问存储功能，是否手动授权?", false, new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Intent localIntent = new Intent();
//                    localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    if (Build.VERSION.SDK_INT >= 9) {
//                        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
//                    } else if (Build.VERSION.SDK_INT <= 8) {
//                        localIntent.setAction(Intent.ACTION_VIEW);
//                        localIntent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
//                        localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//                    }
//                    startActivity(localIntent);
//                }
//            });
//            dialog.show();
        });
        mIvToTop.setOnClickListener(v -> {
            slvHome.setSelection(0);
        });

    }

    static class ViewHolder {

        @Bind(R.id.tv_order_pop_price)
        TextView mTvOrderPopPrice;
        @Bind(R.id.tv_order_pop_sell)
        TextView mTvOrderPopSell;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
//    @Override
//    public void addGallery(List<Products> productses, List<Notice> notices, String moreTipUrl) {
//        productsList.clear();
//        productsList.addAll(productses);
//        homeHeaderGallery = new HomeHeaderGallery(getActivity());
//        homeHeaderGallery.setNotices(notices);
//        homeHeaderGallery.setMoreTipUrl(moreTipUrl);
//        homeHeaderGallery.fillView(productses, slvHome);
//    }


    @Override
    public void addBanner(List<CenterAd> centerAds) {
        homeHeaderBanner = new HomeHeaderBanner(getActivity());
        homeHeaderBanner.fillView(centerAds, slvHome);
    }

    @Override
    public void addType(List<Product> hotProduct, List<Product> newProduct) {
        //第一次加载,存放热卖和人气商品的前10个

        if (hotProduct.size() != 0 || newProduct.size() != 0) {
            hotProducts.addAll(hotProduct);
            newProducts.addAll(newProduct);
            curProducts.addAll(hotProducts);
            homeTypeAdapter = new HomeTypeAdapter(context, curProducts);
            homeTypeAdapter.setAdapterType(1);

            //购物车可见时设置动画
            homeTypeAdapter.setAddClick(new HomeTypeAdapter.addClick() {
                @Override
                public void add(View view) {
                    mCartAnimUtil.setFromView(view);
                    mCartAnimUtil.setRootView(mFlHome);
                    mCartAnimUtil.setToView(mIvFragmentHomeCart);
                    mCartAnimUtil.startAnim();
                }
            });


            slvHome.setAdapter(homeTypeAdapter);
        }
    }


    @Override
    public void addTypeIcon(List<ProductClasses> productClasses, List<FourAd> dailyActivity, List<Notice> notices, List<CenterAd> noticeTimes) {
        homeHeaderIcons = new HomeHeaderIcons(getActivity());
        homeHeaderIcons.setTabChangeListener(new HomeHeaderIcons.tabChangeListener() {
            @Override
            public void change(int tabId) {
                if (tabId == 0 && curPosition != 0) {
                    curProducts.clear();
                    curProducts.addAll(hotProducts);

                    slvHome.setLoadMoreEnable(true, false);
                    homeTypeAdapter.setAdapterType(1);
                    mTlFragmentHomeTop.getTabAt(tabId).select();
                    homeTypeAdapter.notifyDataSetChanged();
                    curPosition = 0;
                } else if (tabId == 1 && curPosition != 1) {
                    slvHome.setLoadMoreEnable(false, false);
                    homeTypeAdapter.setAdapterType(2);
                    mTlFragmentHomeTop.getTabAt(tabId).select();
                    curProducts.clear();
                    curProducts.addAll(newProducts);
                    homeTypeAdapter.notifyDataSetChanged();
                    curPosition = 1;
                }


            }
        });
        homeHeaderIcons.setDailyActivity(dailyActivity);
        homeHeaderIcons.setNoticeTimes(noticeTimes);
        homeHeaderIcons.setNotices(notices);
        homeHeaderIcons.fillView(productClasses, slvHome);
    }

    @Override
    public void setProductState(ProductState productState) {
        //获取最近的可用日期
        for (WeekdayState wks : productState.getData()
                ) {
            if (wks.getState().equals("2")) {
                chooseDate = wks.getWdate();
                return;
            }
        }
    }

    @Override
    public void refreshData(Home home) {
        if (isLoadFailure) {
            presenter.getHome();
            isLoadFailure = false;
            return;
        }
        page = 1;
//        homeHeaderGallery.setNotices(home.getData().getNotice());
//        homeHeaderGallery.refreshView(home.getData().getProducts());

        homeHeaderIcons.setDailyActivity(home.getData().getDailyActivity());
        homeHeaderIcons.setNotices(home.getData().getNotice());
        homeHeaderIcons.setNoticeTimes(home.getData().getNoticeTime());
        homeHeaderIcons.refreshView(home.getData().getProductClasses());
        homeHeaderBanner.refreshView(home.getData().getCenterAd());

        homeHeaderBanner.refreshView(home.getData().getCenterAd());
        //刷新完成后，清空curProducts容器和hotProducts，添加前10个
        curProducts.clear();
        hotProducts.clear();
        newProducts.clear();
        hotProducts.addAll(home.getData().getHotProduct());
        curProducts.addAll(home.getData().getHotProduct());
        newProducts.addAll(home.getData().getNewProduct());
        homeTypeAdapter.notifyDataSetChanged();

        slvHome.setLoadMoreEnable(true, false);
        mTlFragmentHomeTop.getTabAt(0).select();
        homeHeaderIcons.setCurPosition(0);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间

        String time = formatter.format(curDate);
        slvHome.setRefreshTime(time);


    }

    @Override
    public void loadMoreProduct(ProductDetail hotProduct) {
        //加载更多时，更新hotProducts 容器，添加到curProducts中notifydatasetchange
        hotProducts.addAll(hotProduct.getData());
        curProducts.clear();
        curProducts.addAll(hotProducts);
        homeTypeAdapter.notifyDataSetChanged();
        if (hotProduct.getData().size() != 10) {
            slvHome.setLoadMoreEnable(false, true);
        }
    }

    @Override
    public void stopRefesh() {
        slvHome.stopRefresh();
        slvHome.stopLoadMore();
    }

    @Override
    public void showAd(ActivityAd activityAd) {
//        if (isFristLoadAd) {
//            isFristLoadAd = false;
        if (isNeedShowAd) {
            Intent intent = new Intent(getActivity(), HomeAdActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle mBundle = new Bundle();
            mBundle.putSerializable("ad", activityAd);
            intent.putExtras(mBundle);
            startActivity(intent);
        }
//        }

        slvHome.setLoadMoreEnable(true, false);
    }

    @Override
    public void showFailure() {
        isLoadFailure = true;
        if (homeTypeAdapter == null) {
            slvHome.setAdapter(null);
        }
    }

    @Override
    public void updateVersion(Version version) {

        int permission = ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
//        //1、检测没有存储卡权限，请求。
//        //2、第二次进入检测已经有存储卡权限，下载。
//        if (permission != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(getActivity(), PERMISSIONS_STORAGE,
//                    REQUEST_EXTERNAL_STORAGE);
//        }else {
        Message message = new Message();
        message.what = VersionUtil.VERSION_RESULT;
        if (version != null) {
            String oldVersion = VersionUtil
                    .getCurrentVersion(getActivity());
            String lastVersion = version.getData().getAndroid();
            if (!VersionUtil.isNeedUpdate(lastVersion,
                    oldVersion)) {
                message.arg2 = 0;// 不更新
            } else {
                message.arg2 = 1;// 更新
                message.obj = version.getData();
            }
        } else {
            message.arg1 = 1;
            message.obj = "网络出错";
        }
        handler.handleMessage(message);
//        }
    }

    @Override
    public void clear() {
        page = 1;
        slvHome.removeAllViews();
        slvHome.setAdapter(null);
    }


    /**
     * 创建通知
     */
    @SuppressWarnings("deprecation")
    public void setUpNotification() {
        int icon = R.mipmap.ic_launcher;
        CharSequence tickerText = "开始下载";
        long when = System.currentTimeMillis();
        mNotification = new Notification(icon, tickerText, when);
        // 放置在"正在运行"栏目中
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        RemoteViews contentView = new RemoteViews(getActivity()
                .getPackageName(), R.layout.layout_download);
        contentView.setTextViewText(R.id.name, "zaofan.apk 正在下载...");
        // 指定个性化视图
        mNotification.contentView = contentView;

        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    // 处理标题栏颜色渐变
    private void handleTitleBarColorEvaluate() {
        float fraction;
        if (adViewTopSpace > 0) {
            fraction = 1f - adViewTopSpace * 1f / 60;
            if (fraction < 0f) fraction = 0f;
            rlHomeTitle.setAlpha(fraction);
            return;
        }

        float space = Math.abs(adViewTopSpace) * 1f;
        fraction = space / (adViewHeight - titleViewHeight);
        if (fraction < 0f) fraction = 0f;
        if (fraction > 1f) fraction = 1f;
        rlHomeTitle.setAlpha(1f);

        if (fraction >= 1f || isStickyTop) {
            //isStickyTop = true;
            rlHomeTitle.setBackgroundColor(context.getResources().getColor(R.color.main_color));
        } else {
            rlHomeTitle.setBackgroundColor(ColorUtil.getNewColorByStartEndColor(context, fraction, R.color.transparent, R.color.main_color));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUpdate(UpdateEvent event) {
        presenter.checkVersion();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventScroll(ScrollEvent event) {
//        slvHome.smoothScrollBy(homeHeaderGallery.getHeight() + homeHeaderBanner.getSpaceTop() - 200, 1000);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CartEvent event) {
        if (event.getTotalPrice() < 0) {
            event.setTotalPrice(0);
        }
        if (event.getTotalNum() < 0) {
            event.setTotalNum(0);
        }
        mTvFragmentHomeCartPrice.setText("￥" + String.format("%.1f", event.getTotalPrice()));
        mTvFragmentHomeCartCount.setText(event.getTotalNum() + "");
    }


    @Override
    public void onResume() {
        super.onResume();
        //刷新homeTypeAdapter 中的购物车对象,页面切换时购物车参数能正确响应
        if (homeTypeAdapter != null) {
            homeTypeAdapter.initCommonCart(context);
            homeTypeAdapter.notifyDataSetChanged();
        }
        if (Constant.getCityData() == null) {

        } else {
            tvHomeCity.setText(Constant.getCityData().getCityName());
        }
        if (hotProducts.size() != 0 && newProducts.size() != 0) {
            curProducts.clear();
            if (curPosition == 0) {
                curProducts.addAll(hotProducts);
            } else {
                curProducts.addAll(newProducts);
            }
        }
        if (isNeedRefresh) {

            isNeedRefresh = false;
            presenter.refresh();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //用户注销后首页点餐数量清零
        if (!hidden) {
            if (Constant.getUserData() == null) {
                if (hotProducts.size() != 0 && newProducts.size() != 0) {
                    curProducts.clear();
                    if (curPosition == 0) {
                        curProducts.addAll(hotProducts);
                    } else {
                        curProducts.addAll(newProducts);
                    }


                }
            }
        }
        //刷新homeTypeAdapter 中的购物车对象,页面切换时购物车参数能正确响应
        if (homeTypeAdapter != null) {
            homeTypeAdapter.initCommonCart(context);
            homeTypeAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onLowMemory() {
        // TODO Auto-generated method stub
        if (mCartAnimUtil != null) {
            try {
                //移除添加购物车中多创建的ImageView
                mCartAnimUtil.getRootView().removeAllViews();
            } catch (Exception e) {
                e.printStackTrace();
            }
            super.onLowMemory();
        }
    }
}
